package com.joey.cloud.zuul.filter;

import com.joey.cloud.communal.constant.BaseConstant;
import com.joey.cloud.communal.utils.ResponseUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;

/**
 * 异常统一处理
 * @author joey
 */
@Component
@Slf4j
public class ExceptionFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return BaseConstant.FILTER_TYPE_ERROE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        Throwable e = ctx.getThrowable();
        ResponseUtil res = null;
        log.error("全局异常捕获",e);
        if(e instanceof MethodArgumentNotValidException){
            res = ResponseUtil.error(((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage());
        }else if(e instanceof ExpiredJwtException){
            res = ResponseUtil.noAuthority2();
        }else {
            res = ResponseUtil.error("zuul全局异常捕获");
        }
        ResponseUtil.handle(res);
        return null;
    }
}
